package ldk.easytouch.helper;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.graphics.Rect;

import ldk.easytouch.R;

/**
 * Created by ldkxingzhe on 2016/9/13.
 */
public class PositionHelper {
    @SuppressWarnings("unused")
    private static final String TAG = "PositionHelper";

    private static PositionHelper s_Instance;

    private Point mCenterPoint;
    private int mOriginPointDiameter;

    private PositionHelper(){
        mCenterPoint = new Point();
    }

    public static PositionHelper getInstance(){
        if(s_Instance == null){
            s_Instance = new PositionHelper();
        }
        return s_Instance;
    }

    private static final String CENTER_X = "center_x";
    private static final String CENTER_Y = "center_Y";
    public void readFromCache(Context context){
        mOriginPointDiameter = context.getResources().getDimensionPixelSize(R.dimen.origin_point_diameter);
        SharedPreferences positionSaver = getPositionPreferences(context);
        int centerX = positionSaver.getInt(CENTER_X, mOriginPointDiameter / 2);
        int centerY = positionSaver.getInt(CENTER_Y, mOriginPointDiameter / 2 + 100);
        mCenterPoint.set(centerX, centerY);
    }

    public void writeToCache(Context context){
        SharedPreferences.Editor editor = getPositionPreferences(context).edit();
        editor.putInt(CENTER_X, mCenterPoint.x);
        editor.putInt(CENTER_Y, mCenterPoint.y);
    }
    private SharedPreferences getPositionPreferences(Context context){
        return context.getSharedPreferences("position", Context.MODE_PRIVATE);
    }

    public void setCenter(int centerX, int centerY){
        mCenterPoint.set(centerX, centerY);
        InstrumentHelper.getInstance().updateXY(centerX - mOriginPointDiameter/2 ,
                centerY - mOriginPointDiameter/2);
    }

    public int getCenterX(){
        return mCenterPoint.x;
    }

    public int getCenterY(){
        return mCenterPoint.y;
    }

    public Rect calculateRect(int width, int height){
        Point point = calculateLeftUpPoint(width, height);
        return new Rect(point.x, point.y, point.x + width, point.y + height);
    }

    public Point getOriginPointLeftUp(){
        return calculateLeftUpPoint(mOriginPointDiameter, mOriginPointDiameter);
    }

    public Point calculateLeftUpPoint(int width, int height){
        int halfWidth = width / 2;
        int halfHeight = height / 2;
        int leftX = Math.max(0, getCenterX() - halfWidth);
        int upY = Math.max(0, getCenterY() - halfHeight);
        return new Point(leftX, upY);
    }
}
